package com.hwx.app.redis.starter.lock.impl;



import com.hwx.app.redis.starter.lock.DistributedLocker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedissonDistributedLocker implements DistributedLocker {

    @Resource
    private RedissonClient redissonClient;

    @Override
    public RLock lock(String lockKey) {
        synchronized (lockKey) {
            RLock lock = redissonClient.getLock(lockKey);
            lock.lock();
            return lock;
        }
    }

    @Override
    public RLock lock(String lockKey, long leaseTime) {
        synchronized (lockKey) {
            RLock lock = redissonClient.getLock(lockKey);
            lock.lock(leaseTime, TimeUnit.SECONDS);
            return lock;
        }

    }

    @Override
    public RLock lock(String lockKey, TimeUnit unit, long timeout) {
        synchronized (lockKey) {
            RLock lock = redissonClient.getLock(lockKey);
            lock.lock(timeout, unit);
            return lock;
        }
    }

    @Override
    public RLock tryLock(String lockKey, TimeUnit unit, long waitTime, long leaseTime) {
        synchronized (lockKey) {
            RLock lock = redissonClient.getLock(lockKey);
            try {
                boolean b = lock.tryLock(waitTime, leaseTime, unit);
                if (b) {
                    return lock;
                } else {
                    return null;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    @Override
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            if(lock != null){
                lock.unlock();
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }

    }

    @Override
    public void unlock(RLock lock) {
        try {
            if(lock != null){
                lock.unlock();
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

}
